from .models import Users
from utils.serializers import CustomModelSerializer
from rest_framework import serializers
from utils.validator import CustomUniqueValidator
import hashlib
from django.contrib.auth.hashers import make_password
from system.menu.serializers import WebMenuSerializer
from system.menu.models import Menu


class UserInfoSerializer(CustomModelSerializer):
    """
    用户信息-序列化器
    """
    menus = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()
    role_name = serializers.ReadOnlyField(source='role.name')

    class Meta:
        model = Users
        read_only_fields = ['id']
        exclude = ['password']
        extra_kwargs = {
            'post': {'required': False}
        }

    def get_menus(self, obj):
        queryset = Menu.objects.filter(type__lt=2).order_by('sort')
        if not obj.is_superuser:
            menuIds = obj.role.page_perms.all()
            queryset = Menu.objects.filter(id__in=menuIds, status=1, type__in=(0, 1)).order_by('sort')
        serializer = WebMenuSerializer(queryset, many=True)
        return serializer.data

    def get_permissions(self, obj):
        if obj.is_superuser:
            return []
        button = Menu.objects.filter(id__in=obj.role.page_perms.all(), status=1, type=2)
        return [item.permission for item in button] if button else []


class UserSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """
    role_name = serializers.ReadOnlyField(source='role.name')

    class Meta:
        model = Users
        read_only_fields = ['id']
        exclude = ['password']


class UserCreateSerializer(CustomModelSerializer):
    """
    用户新增-序列化器
    """
    username = serializers.CharField(max_length=50,
                                     validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
    password = serializers.CharField(required=False, default=make_password(
        hashlib.md5('admin123456'.encode(encoding='UTF-8')).hexdigest()))

    class Meta:
        model = Users
        fields = "__all__"
        read_only_fields = ["id"]


class UserUpdateSerializer(CustomModelSerializer):
    """
    用户修改-序列化器
    """
    username = serializers.CharField(max_length=50,
                                     validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
    password = serializers.CharField(required=False, allow_blank=True)

    class Meta:
        model = Users
        read_only_fields = ["id"]
        fields = "__all__"
